#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
bool parase(const std::string &src, std::vector<std::string> &s)
{
    size_t idx = 0, pos = 0;
    // 请求方法查找
    pos = src.find(" ", idx);
    if (pos == std::string::npos)
        return false;
    std::string method = src.substr(idx, pos - idx);
    std::transform(method.begin(), method.end(), method.begin(), toupper);
    if (method != "GET" && method != "POST" && method != "DELETE" && method != "HEAD" && method != "PUT")
    {
        printf("请求方法匹配失败");
        return false;
    }
    s.push_back(method);
    // 资源路径查找
    idx = pos + 1;
    pos = src.find("?", idx);
    if (pos == std::string::npos)
    {
        pos = src.find(" ", idx);
        if (pos == std::string::npos)
            return false;
    }
    std::string uri = src.substr(idx, pos - idx);
    s.push_back(uri);
    // 头部字段查找
    if (src[pos] != '?') // 没有头部字段
        s.push_back("");
    else // 有头部字段
    {
        idx = pos + 1;
        pos = src.find(" ", idx);
        if (pos == std::string::npos)
            return false;
        std::string query = src.substr(idx, pos - idx);
        s.push_back(query);
    }
    // http版本
    idx = pos + 1;
    if (src.back() == '\n')
    {
        std::string http_version;
        if (src[src.size() - 2] == '\r')
            http_version = src.substr(idx, src.size() - 2 - idx);
        else
            http_version = src.substr(idx, src.size() - 1 - idx);
        s.push_back(http_version);
    }
    return true;
}
int main()
{
    std::string str="get root/help http/1.1\n";
    std::vector<std::string> vec;
    bool ret=parase(str,vec);
    if(ret==false)
        return -1;
    std::cout<<"method:"<<vec[0]<<std::endl;
    std::cout<<"uri:"<<vec[1]<<std::endl;
    std::cout<<"header:"<<vec[2]<<std::endl;
    std::cout<<"http:"<<vec[3]<<std::endl;
}